﻿using Dotnet.TopApi;
using Dotnet.TopApi.Parser;
using Dotnet.TopApi.Request;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dotnet.Sui
{
    public class SuiClient: DefaultTopClient
    {
        public SuiClient() : base("https://www.sui.com/")
        {

        }

        protected override T DoExecute<T>(ITopRequest<T> request, string session, DateTime timestamp)
        {
            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return CreateErrorResponse<T>(e.ErrorCode, e.ErrorMsg);
            }

            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            string reqUrl = this.serverUrl + request.GetApiName();// webUtils.BuildUrl(, txtParams);
            // 解释响应结果
            T rsp;
            try
            {
                string body = "";
                if (txtParams.GetHeadMethod() == "GET")
                {
                    body = webUtils.DoGet(reqUrl, txtParams);
                }
                else
                {
                    body = webUtils.DoPost(reqUrl, txtParams);
                }
                if (body.Trim().Contains("<!DOCTYPE html>"))
                {
                    disableParser = true;
                }
                if (disableParser)
                {
                    rsp = Activator.CreateInstance<T>();
                    rsp.Body = body;
                }
                else
                {
                    ITopParser tp = new TopJsonParser();
                    rsp = tp.Parse<T>(body);
                }
                // 追踪错误的请求
                if (!disableTrace && rsp.IsError)
                {
                    StringBuilder sb = new StringBuilder(reqUrl).Append(" response error!\r\n").Append(rsp.Body);
                    topLogger.Warn(sb.ToString());
                }
                rsp.ReqUrl= reqUrl;
                return rsp;
            }
            catch (Exception e)
            {
                if (!disableTrace)
                {
                    StringBuilder sb = new StringBuilder(reqUrl).Append(" request error!\r\n").Append(e.StackTrace);
                    topLogger.Error(sb.ToString());
                }
                throw e;
            }
        }
    }
}
